﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Collections;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using PlanningGIS.Win.Controls;
using PlanningGIS.ArcGIS;
using PlanningGIS.Util.Log;

namespace PlanningGIS.Symbol
{
    /// <summary>
    /// 唯一值渲染
    /// </summary>
    public partial class UniqueValueRenderer : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public UniqueValueRenderer()
        {
            InitializeComponent();            
        }

        /// <summary>
        /// 要符号化的图层
        /// </summary>
        private IFeatureLayer _FeatureLayer;

        /// <summary>
        /// 获取或设置要符号化的图层
        /// </summary>
        public IFeatureLayer FeatureLayer
        {
            set
            {
                _FeatureLayer = value;
                try
                {
                    cmbColorRamp.Init();
                    if (_FeatureLayer == null || _FeatureLayer.FeatureClass == null) return;
                    cmbFields1.Items.Clear();
                    cmbFields2.Items.Clear();
                    cmbFields3.Items.Clear();
                    IFeatureClass featcls = _FeatureLayer.FeatureClass;
                    for (int i = 0; i < featcls.Fields.FieldCount; i++)
                    {
                        IField fd = featcls.Fields.get_Field(i);
                        string Name = fd.Name.Trim();
                        switch (fd.Type)
                        {
                            case esriFieldType.esriFieldTypeDouble:
                            case esriFieldType.esriFieldTypeInteger:
                            case esriFieldType.esriFieldTypeSmallInteger:
                            case esriFieldType.esriFieldTypeString:
                                this.cmbFields1.Items.Add(Name);
                                this.cmbFields2.Items.Add(Name);
                                this.cmbFields3.Items.Add(Name);
                                break;
                        }
                    }
                    Init();
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorText(ex);
                }
                
            }
            get
            {
                return _FeatureLayer;
            }
        }

        /// <summary>
        /// 唯一值渲染对象
        /// </summary>
        private IUniqueValueRenderer _UniqueValueRender = null;
        
        /// <summary>
        /// 获取设置后的符号
        /// </summary>
        public IUniqueValueRenderer ValueRenderer
        {
            get
            {
                try
                {
                    //for (int i = 0; i < _UniqueValueRender.ValueCount; i++)
                    //{
                    //    _UniqueValueRender.set_Symbol(this._UniqueValueRender.get_Value(i), (ISymbol)_SymbolList[i + 1]);
                    //}
                    return _UniqueValueRender;
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 初始化对象
        /// </summary>
        private void Init()
        {
            if (FeatureLayer == null || !(FeatureLayer is IGeoFeatureLayer)) return;
            IFeatureRenderer renderer = (FeatureLayer as IGeoFeatureLayer).Renderer;
            if (renderer == null || !(renderer is IUniqueValueRenderer)) return;
            this._UniqueValueRender = (IUniqueValueRenderer)renderer;
            if (_UniqueValueRender == null) return;
            if (_UniqueValueRender.FieldCount > 0)
            {
                this.cmbFields1.Enabled = true;
                this.chkField1.Checked = true;
                this.cmbFields1.Text = _UniqueValueRender.get_Field(0).ToString();
            }
            if (_UniqueValueRender.FieldCount > 1)
            {
                this.cmbFields2.Enabled = true;
                this.chkField2.Checked = true;
                this.cmbFields2.Text = _UniqueValueRender.get_Field(1).ToString();
            }
            if (_UniqueValueRender.FieldCount > 2)
            {
                this.cmbFields3.Enabled = true;
                this.chkField3.Checked = true;
                this.cmbFields3.Text = _UniqueValueRender.get_Field(2).ToString();
            }
            if (_UniqueValueRender.FieldCount > 0)
            {
                cmbColorRamp.ColorScheme = _UniqueValueRender.ColorScheme;
                AddFieldValue2();
            }
        }

        /// <summary>
        /// 增加所有值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddAllValue_Click(object sender, EventArgs e)
        {
            int fieldCount = 0;
            List<string> sFieldName = new List<string>();
            if (this.chkField1.Checked)
            {
                if (this.cmbFields1.SelectedIndex < 0)
                {
                    MsgHelper.ShowErrorMsgbox(this.GetParentForm(), "没有选择字段1，请选择字段1！");
                    return;
                }
                fieldCount = 1;
                sFieldName.Add(cmbFields1.Text);
            }
            if (this.chkField2.Checked)
            {
                if (this.cmbFields2.SelectedIndex < 0)
                {
                    MsgHelper.ShowErrorMsgbox(this.GetParentForm(), "没有选择字段2，请选择字段2！");
                    return;
                }
                fieldCount = 2;
                sFieldName.Add(cmbFields2.Text);
            }
            if (this.chkField3.Checked)
            {
                if (this.cmbFields3.SelectedIndex < 0)
                {
                    MsgHelper.ShowErrorMsgbox(this.GetParentForm(), "没有选择字段3，请选择字段3！");
                    return;
                }
                fieldCount = 3;
                sFieldName.Add(cmbFields3.Text);
            }
            if (fieldCount < 1)
            {
                MsgHelper.ShowErrorMsgbox(this.GetParentForm(), "没有选择字段，请选择字段！");
                return;
            }
            dgrdvwRender.Rows.Clear();            
            progressBarX1.Visible = true;
            this.Cursor = Cursors.WaitCursor;
            Application.DoEvents();
            try
            {
                this._UniqueValueRender = CreatUniqueRenderer(fieldCount, sFieldName);
                if (this._UniqueValueRender == null) return;
                if (this._UniqueValueRender.ValueCount > 500)
                {
                    DialogResult dia = MsgHelper.ShowYesOrNoQueryMsgBox("唯一值多于500个，是否继续生成列表？如果继续，时间较长，请耐心等待……");
                    if (dia != DialogResult.Yes)  return;
                }
                this._UniqueValueRender.UseDefaultSymbol = cbxUseDefaultSymbol.Checked;
                this._UniqueValueRender.ColorScheme = cmbColorRamp.ColorScheme;
                AddFieldValue2();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, ex.Message);
            }
            finally
            {
                GC.Collect();
                this.Cursor = Cursors.Default;
                progressBarX1.Visible = false;
            }
        }

        /// <summary>
        /// 创建唯一值渲染，最新方法，多个波段时只取图层中存在的唯一值
        /// </summary>
        /// <param name="fieldCount">字段个数</param>
        /// <returns></returns>
        private IUniqueValueRenderer CreatUniqueRenderer(int fieldCount,List<string> sFieldName)
        {
            IGeoFeatureLayer geoLayer = _FeatureLayer as IGeoFeatureLayer;
            IUniqueValueRenderer renderer = new UniqueValueRendererClass();
            renderer.FieldCount = fieldCount;
            if (fieldCount > 0)
            {
                renderer.set_Field(0, cmbFields1.Text);
            }
            if (fieldCount > 1)
            {
                renderer.FieldDelimiter = ",";
                renderer.set_Field(1, cmbFields2.Text);
            }
            if (fieldCount > 2)
            {
                renderer.set_Field(2, cmbFields3.Text);
            }

            List<string> values = new List<string>();

            if (sFieldName.Count == 1)
            {
                values = FieldHelper.GetUniqueValueByDataStatistics(_FeatureLayer.FeatureClass, sFieldName[0]);
            }
            else if (sFieldName.Count > 1)
            {
                values = GetMultiUniqueValue(_FeatureLayer, sFieldName);
            }

            if (values.Count == 0) return null;
            IColorRamp myColorRamp = cmbColorRamp.SelectedColorRamp;

            int cnt = values.Count;
            for (int j = 0; j <= cnt; j++)
            {
                ISymbol isymbol = GetSymbolColorRamp(myColorRamp, j, cnt + 1);
                if (j == cnt)
                {
                    renderer.DefaultSymbol = isymbol;
                }
                else
                {
                    if (values[j].ToString().Replace(",", "").Trim() != "")
                    {
                        renderer.AddValue(values[j].ToString(), "", isymbol);
                        renderer.Label[values[j].ToString()] = values[j].ToString();
                    }
                }
            }
            values.Clear();
            GC.Collect();
            return renderer;
        }

        /// <summary>
        /// 创建唯一值渲染,最初的方法，多个波段时取的唯一值数量太多，存在一定问题
        /// </summary>
        /// <param name="fieldCount">字段个数</param>
        /// <returns></returns>
        private IUniqueValueRenderer CreatUniqueValueRenderer(int fieldCount)
        {
            IGeoFeatureLayer geoLayer = _FeatureLayer as IGeoFeatureLayer;
            IUniqueValueRenderer renderer = new UniqueValueRendererClass();
            renderer.FieldCount = fieldCount;
            if (fieldCount > 0)
                renderer.set_Field(0, cmbFields1.Text);
            if (fieldCount > 1)
            {
                renderer.FieldDelimiter = ",";
                renderer.set_Field(1, cmbFields2.Text);
            }
            if (fieldCount > 2)
                renderer.set_Field(2, cmbFields3.Text);

            ArrayList list1 = new ArrayList();
            ArrayList list2 = new ArrayList();
            ArrayList list3 = new ArrayList();

            if (fieldCount > 0)
                list1 = FieldHelper.GetUniqueValuesByQueryDef(_FeatureLayer.FeatureClass, cmbFields1.Text, false);
            //list1 = FieldHelper.GetUniqueValue(_FeatureLayer.FeatureClass, cmbFields1.Text);
            if (fieldCount > 1)
                list2 = FieldHelper.GetUniqueValuesByQueryDef(_FeatureLayer.FeatureClass, cmbFields2.Text, false);
            //list2 = FieldHelper.GetUniqueValue(_FeatureLayer.FeatureClass, cmbFields2.Text);
            if (fieldCount > 2)
                list3 = FieldHelper.GetUniqueValuesByQueryDef(_FeatureLayer.FeatureClass, cmbFields3.Text, false);
            //list3 = FieldHelper.GetUniqueValue(_FeatureLayer.FeatureClass, cmbFields3.Text);
            List<string> values = new List<string>();
            for (int i = 0; i < list1.Count; i++)
            {
                if (fieldCount > 1)
                {
                    for (int j = 0; j < list2.Count; j++)
                    {
                        if (fieldCount > 2)
                        {
                            for (int k = 0; k < list3.Count; k++)
                            {
                                values.Add(list1[i].ToString() + "," + list2[j].ToString() + "," + list3[k].ToString());
                            }
                        }
                        else
                        {
                            values.Add(list1[i].ToString() + "," + list2[j].ToString());
                        }
                    }
                }
                else
                {
                    values.Add(list1[i].ToString());
                }
            }
            if (values.Count == 0) return null;
            IColorRamp myColorRamp = cmbColorRamp.SelectedColorRamp;

            int cnt = values.Count;
            for (int j = 0; j <= cnt; j++)
            {
                ISymbol isymbol = GetSymbolColorRamp(myColorRamp, j, cnt + 1);
                if (j == cnt)
                {
                    renderer.DefaultSymbol = isymbol;
                }
                else
                {
                    if (values[j].ToString().Replace(",", "").Trim() != "")
                    {
                        renderer.AddValue(values[j].ToString(), "", isymbol);
                        renderer.Label[values[j].ToString()] = values[j].ToString();
                    }
                }
            }
            list1.Clear(); list2.Clear(); list3.Clear();
            values.Clear();
            GC.Collect();
            return renderer;
        }

        /// <summary>
        /// 获取多个字段的唯一值
        /// </summary>
        /// <param name="pFeatLyr"></param>
        /// <param name="sFieldName"></param>
        /// <returns></returns>
        private List<string> GetMultiUniqueValue(IFeatureLayer pFeatLyr, List<string> sFieldName)
        {
            ITable pTable;
            IRow pNextRow;
            IQueryFilter pQueryFilter = new QueryFilterClass();
            List<string> values = new List<string>();
            IGeoFeatureLayer pGeoFeatureL = (IGeoFeatureLayer)pFeatLyr;
            pTable = (ITable)pGeoFeatureL;

            List<int> pFieldIndex = new List<int>();
            pQueryFilter = new QueryFilterClass();

            for (int i=0;i<sFieldName.Count;i++)
            {
                pQueryFilter.AddField(sFieldName[i]);
                int pFieldNumber = pTable.FindField(sFieldName[i]);
                pFieldIndex.Add(pFieldNumber);
            }

            ICursor pCursor = pTable.Search(pQueryFilter, true);

            pNextRow = pCursor.NextRow();


            while (pNextRow != null)
            {
                string codeValue = "";
                for (int j=0;j<pFieldIndex.Count;j++)
                {
                    if (j == pFieldIndex.Count - 1) codeValue = codeValue + pNextRow.get_Value(pFieldIndex[j]).ToString();
                    else codeValue = codeValue + pNextRow.get_Value(pFieldIndex[j]).ToString() + ",";
                }
                if (!values.Contains(codeValue))
                    values.Add(codeValue);
                pNextRow = pCursor.NextRow();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor);
            return values;
        }
        /// <summary>
        /// 添加值
        /// </summary>
        private void AddFieldValue()
        {
            dgrdvwRender.Rows.Clear();
            Application.DoEvents();
            dgrdvwRender.Enabled = false;
            if (this._UniqueValueRender == null) return;
            try
            {
                cbxUseDefaultSymbol.Checked = _UniqueValueRender.UseDefaultSymbol;
                int idx = dgrdvwRender.Rows.Add();
                
                ISymbol symbol = _UniqueValueRender.DefaultSymbol;
                dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Value = SymbolHelper.DrawSymbol(symbol, 32, 16);
                dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Tag = symbol;
                dgrdvwRender.Rows[idx].Cells[dgrdvwcolValue.Index].Value = "所有其他值";
                dgrdvwRender.Rows[idx].Cells[dgrdvwcolLabel.Index].Value = _UniqueValueRender.DefaultLabel;
                for (int i = 0; i < _UniqueValueRender.ValueCount; i++)
                {
                    idx = dgrdvwRender.Rows.Add();
                    string value = _UniqueValueRender.get_Value(i);
                    symbol = _UniqueValueRender.get_Symbol(value);
                    dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Value = SymbolHelper.DrawSymbol(symbol, 32, 16);
                    dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Tag = symbol;
                    dgrdvwRender.Rows[idx].Cells[dgrdvwcolValue.Index].Value = value;
                    dgrdvwRender.Rows[idx].Cells[dgrdvwcolLabel.Index].Value = _UniqueValueRender.get_Label(value);
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, ex.Message);
            }
            finally
            {
                dgrdvwRender.Enabled = true;
            }
        }

        public List<Bitmap> bitmaplist = new List<Bitmap>();
        private void AddFieldValue2()
        {
            for (int i = 0; i < dgrdvwRender.RowCount; i++)
            {
                (dgrdvwRender.Rows[i].Cells[dgrdvwcolImg.Index].Value as Bitmap).Dispose();
            }
            dgrdvwRender.Rows.Clear();
            Application.DoEvents();

            dgrdvwRender.Enabled = false;
            if (this._UniqueValueRender == null) return;
            try
            {
                cbxUseDefaultSymbol.Checked = _UniqueValueRender.UseDefaultSymbol;
                int idx = dgrdvwRender.Rows.Add();
                ISymbol symbol = _UniqueValueRender.DefaultSymbol;
                dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Value = SymbolHelper.DrawSymbol(symbol, 32, 16);
                dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Tag = symbol;
                dgrdvwRender.Rows[idx].Cells[dgrdvwcolValue.Index].Value = "所有其他值";
                dgrdvwRender.Rows[idx].Cells[dgrdvwcolLabel.Index].Value = _UniqueValueRender.DefaultLabel;
                if (_UniqueValueRender.ValueCount < 500)
                {
                    for(int j=0;j<bitmaplist.Count;j++)
                    {
                        bitmaplist[j].Dispose();
                    }
                    bitmaplist.Clear();
                    for (int i = 0; i < _UniqueValueRender.ValueCount; i++)
                    {
                        idx = dgrdvwRender.Rows.Add();
                        string value = _UniqueValueRender.get_Value(i);
                        symbol = _UniqueValueRender.get_Symbol(value);
                        Bitmap bitmap= SymbolHelper.DrawSymbol(symbol, 32, 16);
                        bitmaplist.Add(bitmap);
                        dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Value = bitmap;
                        dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Tag = symbol;
                        dgrdvwRender.Rows[idx].Cells[dgrdvwcolValue.Index].Value = value;
                        dgrdvwRender.Rows[idx].Cells[dgrdvwcolLabel.Index].Value = _UniqueValueRender.get_Label(value);
                    }
                }
                else
                {
                    string bitmapdir = Application.StartupPath + "\\bitmap";
                    if (!System.IO.Directory.Exists(bitmapdir))
                    {
                        System.IO.Directory.CreateDirectory(bitmapdir);
                    }
                    for (int i = 0; i < _UniqueValueRender.ValueCount; i++)
                    {
                        idx = dgrdvwRender.Rows.Add();
                        string value = _UniqueValueRender.get_Value(i);
                        symbol = _UniqueValueRender.get_Symbol(value);
                        Bitmap bitmap = SymbolHelper.DrawSymbol(symbol, 32, 16);
                        string bitpath = bitmapdir + "\\bitmap" + i.ToString() + ".jpg";
                        bitmap.Save(bitpath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        bitmap.Dispose();

                        dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Value = GetImage(bitpath);
                        dgrdvwRender.Rows[idx].Cells[dgrdvwcolImg.Index].Tag = symbol;
                        dgrdvwRender.Rows[idx].Cells[dgrdvwcolValue.Index].Value = value;
                        dgrdvwRender.Rows[idx].Cells[dgrdvwcolLabel.Index].Value = _UniqueValueRender.get_Label(value);
                        if (i % 100 == 0) GC.Collect();
                    }
                    System.IO.Directory.Delete(bitmapdir, true);
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, ex.Message);
            }
            finally
            {
                dgrdvwRender.Enabled = true;
            }
        }

        public System.Drawing.Image GetImage(string path)
        {
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
            System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
            fs.Close();
            return result;
        }


        /// <summary>
        /// 渐变色选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbColorRamp_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this._UniqueValueRender == null) return;
            if (dgrdvwRender.Rows.Count == 0) return;
            dgrdvwRender.Enabled = false;
            try
            {                
                IColorRamp colorRamp = cmbColorRamp.SelectedColorRamp;
                int cnt = dgrdvwRender.Rows.Count;
                //ISymbol sym = GetSymbolColorRamp(colorRamp, cnt, cnt+1);
                //dgrdvwRender.Rows[0].Cells[dgrdvwcolImg.Index].Value = SymbolHelper.DrawSymbol(sym, 32, 16); ;
                //dgrdvwRender.Rows[0].Cells[dgrdvwcolImg.Index].Tag = sym;
                //_UniqueValueRender.DefaultSymbol = sym;
                for (int i = 1; i < cnt; i++)
                {
                    ISymbol sym = GetSymbolColorRamp(colorRamp, i - 1, cnt );
                    dgrdvwRender.Rows[i].Cells[dgrdvwcolImg.Index].Value = SymbolHelper.DrawSymbol(sym, 32, 16); ;
                    dgrdvwRender.Rows[i].Cells[dgrdvwcolImg.Index].Tag = sym;
                    _UniqueValueRender.set_Symbol(dgrdvwRender.Rows[i].Cells[dgrdvwcolValue.Index].Value.ToString(), sym);
                }
                this._UniqueValueRender.ColorScheme = cmbColorRamp.ColorScheme;
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, ex.Message);
            }
            finally
            {
                dgrdvwRender.Enabled = true;
            }
        }
        /// <summary>
        /// 获取色带所对应的符号
        /// </summary>
        /// <param name="colorRamp">色带</param>
        /// <param name="index">要取值的索引</param>
        /// <param name="count">总数</param>
        /// <returns></returns>
        private ISymbol GetSymbolColorRamp(IColorRamp colorRamp, int index, int count)
        {
            ISymbol pSymbol = null;
            switch (_FeatureLayer.FeatureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryMultipoint:
                case esriGeometryType.esriGeometryPoint:
                    ISimpleMarkerSymbol dsymbol = new SimpleMarkerSymbolClass();
                    dsymbol.Color = colorRamp.get_Color((index * colorRamp.Size) / (count));
                    dsymbol.Outline = true;
                    dsymbol.OutlineSize = 1;
                    dsymbol.OutlineColor = (IColor)ESRI.ArcGIS.ADF.Connection.Local.Converter.ToRGBColor(Color.Black);
                    dsymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                    dsymbol.Size = 4;
                    pSymbol = (ISymbol)dsymbol;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                case esriGeometryType.esriGeometryLine:
                    ISimpleLineSymbol xsymbol = new SimpleLineSymbolClass();
                    xsymbol.Color = colorRamp.get_Color((index * colorRamp.Size) / (count));
                    xsymbol.Width = 0.4;
                    pSymbol = (ISymbol)xsymbol;
                    break;
                case esriGeometryType.esriGeometryPolygon:
                    ISimpleFillSymbol msymbol = new SimpleFillSymbolClass();
                    msymbol.Color = colorRamp.get_Color((index * colorRamp.Size) / (count));
                    msymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                    msymbol.Outline.Width = 0.4;
                    pSymbol = (ISymbol)msymbol;
                    break;
                default:
                    break;
            }
            //GC.Collect();
            return pSymbol;
        }

        /// <summary>
        /// 是否选用默认的颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxUseDefaultSymbol_CheckedChanged(object sender, EventArgs e)
        {
            if (_UniqueValueRender != null)
                this._UniqueValueRender.UseDefaultSymbol = cbxUseDefaultSymbol.Checked;
        }

        /// <summary>
        /// 选择字段1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkField1_CheckedChanged(object sender, EventArgs e)
        {
            this.cmbFields1.Enabled = this.chkField1.Checked;
            if (this.chkField1.Checked)
            {
                this.chkField2.Enabled = true;
                if (cmbFields1.SelectedIndex < 0) cmbFields1.SelectedIndex = 0;
            }
            else
            {
                this.chkField2.Enabled = false;
                this.chkField3.Enabled = false;
                this.chkField2.Checked = false;
                this.chkField3.Checked = false;
            }
        }

        /// <summary>
        /// 选择字段2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkField2_CheckedChanged(object sender, EventArgs e)
        {
            this.cmbFields2.Enabled = this.chkField2.Checked;
            if (this.chkField2.Checked)
            {
                this.chkField3.Enabled = true;
                if (cmbFields2.SelectedIndex < 0) cmbFields2.SelectedIndex = 0;
            }
            else
            {
                this.chkField3.Enabled = false;
                this.chkField3.Checked = false;
            }
        }

        /// <summary>
        /// 选择字段3
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkField3_CheckedChanged(object sender, EventArgs e)
        {
            this.cmbFields3.Enabled = this.chkField3.Checked;
            if (this.chkField3.Checked)
                if (cmbFields3.SelectedIndex < 0) cmbFields3.SelectedIndex = 0;
        }

        /// <summary>
        /// 双击图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwRender_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
            if (e.ColumnIndex == dgrdvwcolImg.Index)
            {
                ISymbol pSymbol = (ISymbol)dgrdvwRender.Rows[e.RowIndex].Cells[dgrdvwcolImg.Index].Tag;
                FrmVectorStyle.ShowStyle(pSymbol,this.ParentForm, new SymbolChanged((obj, sym) =>
                {
                    if (sym != null && sym.NewSymbol != null)
                    {
                        pSymbol = sym.NewSymbol;
                        dgrdvwRender.Rows[e.RowIndex].Cells[dgrdvwcolImg.Index].Tag = pSymbol;
                        dgrdvwRender.Rows[e.RowIndex].Cells[dgrdvwcolImg.Index].Value = SymbolHelper.DrawSymbol(pSymbol, 32, 16);
                        if (e.RowIndex == 0)
                        {
                            _UniqueValueRender.DefaultSymbol = null;
                            _UniqueValueRender.DefaultSymbol = pSymbol;
                        }
                        else
                        {
                            _UniqueValueRender.set_Symbol(dgrdvwRender.Rows[e.RowIndex].Cells[dgrdvwcolValue.Index].Value.ToString(), pSymbol);
                        }
                    }
                }));                
            }
        }

        /// <summary>
        /// 合并分组
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnubtnGroup_Click(object sender, EventArgs e)
        {
            if (dgrdvwRender.SelectedRows.Count < 1) return;
            string value = "";
            string txt = "";
            int idx = 999;
            foreach (DataGridViewRow itm in dgrdvwRender.SelectedRows)
            {
                value += itm.Cells[dgrdvwcolValue.Index].Value.ToString() + ";";
                txt += itm.Cells[dgrdvwcolLabel.Index].Value.ToString() + ";";
                if (idx > itm.Index) idx = itm.Index;
            }
            for (int i = dgrdvwRender.RowCount - 1; i >= idx; i--)
            {
                DataGridViewRow itm = dgrdvwRender.Rows[i];
                if (!itm.Selected) continue;
                string v = itm.Cells[dgrdvwcolValue.Index].Value.ToString();
                _UniqueValueRender.RemoveValue(v);
                if (i != idx)
                    dgrdvwRender.Rows.Remove(itm);
                else
                {
                    _UniqueValueRender.AddValue(value, txt, itm.Cells[dgrdvwcolImg.Index].Tag as ISymbol);
                    itm.Cells[dgrdvwcolValue.Index].Value = value;
                    itm.Cells[dgrdvwcolLabel.Index].Value = txt;
                }
            }

        }

        /// <summary>
        /// 取消合并
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mnubtnUnGroup_Click(object sender, EventArgs e)
        {
            if (dgrdvwRender.SelectedRows.Count != 1) return;
            DataGridViewRow dr = dgrdvwRender.SelectedRows[0];
            string v = dr.Cells[dgrdvwcolValue.Index].Value.ToString();
            if (!v.Contains(";")) return;
            int idx = dr.Index;
            string[] values = v.Split(';');
            ISymbol symbol = (ISymbol)dr.Cells[dgrdvwcolImg.Index].Tag;
            for (int i = 0; i < values.Length; i++)
            {
                string tmp = values[i];
                if (string.IsNullOrWhiteSpace(tmp)) continue;
                DataGridViewRow newdr = (DataGridViewRow)dr.Clone();
                newdr.Cells[dgrdvwcolImg.Index].Value = dr.Cells[dgrdvwcolImg.Index].Value;
                newdr.Cells[dgrdvwcolValue.Index].Value = tmp;
                newdr.Cells[dgrdvwcolLabel.Index].Value = tmp;
                newdr.Cells[dgrdvwcolCount.Index].Value = "?";
                newdr.Cells[dgrdvwcolImg.Index].Tag = dr.Cells[dgrdvwcolImg.Index].Tag;
                dgrdvwRender.Rows.Insert(idx + i, newdr);
                _UniqueValueRender.AddValue(tmp, tmp, null);
            }
            dgrdvwRender.Rows.Remove(dr);
            _UniqueValueRender.RemoveValue(v);
        }

        /// <summary>
        /// 选择渲染列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwRender_SelectionChanged(object sender, EventArgs e)
        {
            btnDown.Enabled = false;
            btnUp.Enabled = false;
            btnRemove.Enabled = false;
            mnubtnUnGroup.Enabled = false;
            mnubtnGroup.Enabled = false;
            if (dgrdvwRender.SelectedRows.Count > 0)
            {
                if (dgrdvwRender.SelectedRows.Count == 1)
                {
                    if (dgrdvwRender.SelectedRows[0].Index > 1)
                        btnUp.Enabled = true;
                    if (dgrdvwRender.SelectedRows[0].Index > 0 && dgrdvwRender.SelectedRows[0].Index < dgrdvwRender.Rows.Count - 1)
                        btnDown.Enabled = true;
                    if (dgrdvwRender.SelectedRows[0].Cells[dgrdvwcolValue.Index].Value != null)
                    {
                        string v = dgrdvwRender.SelectedRows[0].Cells[dgrdvwcolValue.Index].Value.ToString();
                        mnubtnUnGroup.Enabled = v.Contains(";");
                    }                    
                }
                else
                {
                    mnubtnGroup.Enabled = true;
                }
                btnRemove.Enabled = true;
            }
        }

        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (dgrdvwRender.SelectedRows.Count < 1) return;
            foreach (DataGridViewRow dr in dgrdvwRender.SelectedRows)
            {
                if (dr.Index == 0) continue;
                string value = dr.Cells[dgrdvwcolValue.Index].Value.ToString();
                _UniqueValueRender.RemoveValue(value);
                dgrdvwRender.Rows.Remove(dr);
            }
        }

        /// <summary>
        /// 上移
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUp_Click(object sender, EventArgs e)
        {
            if (dgrdvwRender.SelectedRows.Count != 1) return;
            DataGridViewRow dr = dgrdvwRender.SelectedRows[0];
            int idx = dr.Index;
            if (idx < 1) return;
            DataGridViewRow newdr = (DataGridViewRow)dr.Clone();
            newdr.Cells[dgrdvwcolImg.Index].Value = dr.Cells[dgrdvwcolImg.Index].Value;
            newdr.Cells[dgrdvwcolValue.Index].Value = dr.Cells[dgrdvwcolValue.Index].Value;
            newdr.Cells[dgrdvwcolLabel.Index].Value = dr.Cells[dgrdvwcolLabel.Index].Value;
            newdr.Cells[dgrdvwcolCount.Index].Value = dr.Cells[dgrdvwcolCount.Index].Value;
            newdr.Cells[dgrdvwcolImg.Index].Tag = dr.Cells[dgrdvwcolImg.Index].Tag;
            dgrdvwRender.Rows.Insert(idx - 1, newdr);
            dgrdvwRender.Rows.RemoveAt(idx + 1);
            SetOnlySelected(idx - 1);
        }

        /// <summary>
        /// 下移
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDown_Click(object sender, EventArgs e)
        {
            if (dgrdvwRender.SelectedRows.Count != 1) return;
            DataGridViewRow dr = dgrdvwRender.SelectedRows[0];
            int idx = dr.Index;
            if (idx == 0 || idx == dgrdvwRender.Rows.Count - 1) return;
            DataGridViewRow newdr = (DataGridViewRow)dr.Clone();
            newdr.Cells[dgrdvwcolImg.Index].Value = dr.Cells[dgrdvwcolImg.Index].Value;
            newdr.Cells[dgrdvwcolValue.Index].Value = dr.Cells[dgrdvwcolValue.Index].Value;
            newdr.Cells[dgrdvwcolLabel.Index].Value = dr.Cells[dgrdvwcolLabel.Index].Value;
            newdr.Cells[dgrdvwcolCount.Index].Value = dr.Cells[dgrdvwcolCount.Index].Value;
            newdr.Cells[dgrdvwcolImg.Index].Tag = dr.Cells[dgrdvwcolImg.Index].Tag;
            dgrdvwRender.Rows.Insert(idx + 2, newdr);
            dgrdvwRender.Rows.RemoveAt(idx);
            SetOnlySelected(idx + 1);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="index"></param>
        private void SetOnlySelected(int index)
        {
            if (dgrdvwRender.SelectedRows != null && dgrdvwRender.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow dr in dgrdvwRender.SelectedRows)
                {
                    dr.Selected = false;
                }
            }
            if (index > dgrdvwRender.RowCount - 1) return;
            dgrdvwRender.Rows[index].Selected = true;
            Application.DoEvents();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwRender_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
            if (!dgrdvwRender.Enabled) return;
            if (e.ColumnIndex == dgrdvwcolLabel.Index)
            {                
                object obj = dgrdvwRender.Rows[e.RowIndex].Cells[dgrdvwcolLabel.Index].Value;
                string txt = (obj == null ? "" : obj.ToString());
                if(e.RowIndex==0)
                {
                    _UniqueValueRender.DefaultLabel = txt;
                }
                else
                {
                    string v = dgrdvwRender.Rows[e.RowIndex].Cells[dgrdvwcolValue.Index].Value.ToString();
                    _UniqueValueRender.set_Label(v, txt);
                }               
            }
        }
    }
}